package com.zhouwd.zcamera;

import android.media.MediaCodec;
import android.media.MediaCodecInfo;
import android.media.MediaFormat;
import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Date;

import static android.media.MediaCodec.MetricsConstants.MIME_TYPE;

public class VideoEncode {
    private static final String TAG = VideoEncode.class.getSimpleName();
    private String mine = "video/avc";
    private int rate = 3500000;
    private int frameRate = 30;
    private int frameInterval = 2;
    private int width = 720;
    private int height = 1280;
    private MediaCodec mediaCodec;
    private long presentationTimeUs;
    private MediaCodec.BufferInfo ebi;

    private FileOutputStream fileOutputStream;

    public VideoEncode() throws IOException {
        String dirName = Environment.getExternalStorageDirectory()+ File.separator + "zhouwd" ;
        File dir = new File(dirName);

        if (!dir.exists()) {
            try {
                //按照指定的路径创建文件夹
                dir.mkdirs();
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }
        }

        String fileName = dirName + File.separator + System.currentTimeMillis() +  ".h264";

        File file = new File(fileName);
        if (!file.exists()) {
            try {
                //在指定的文件夹中创建文件
                file.createNewFile();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        fileOutputStream = new FileOutputStream(file);

        mediaCodec = MediaCodec.createEncoderByType("video/avc");

        MediaFormat format = MediaFormat.createVideoFormat(MediaFormat.MIMETYPE_VIDEO_AVC, width, height);
        format.setInteger(MediaFormat.KEY_BIT_RATE, rate);
        format.setInteger(MediaFormat.KEY_FRAME_RATE, frameRate);
        format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, frameInterval);
        format.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Flexible);
        presentationTimeUs = new Date().getTime() * 1000;
        ebi = new MediaCodec.BufferInfo();

        mediaCodec.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);

    }




    public void start() {
        mediaCodec.start();
    }

    public void encode(byte[] data) {
        Log.i(TAG, "encode: ");
        int index = mediaCodec.dequeueInputBuffer(-1);
        Log.i(TAG, "encode: index -->" + index);
        if (index >= 0) {

            ByteBuffer buffer = mediaCodec.getInputBuffer(index);

            buffer.clear();
            buffer.put(data);

            long pts = new Date().getTime() * 1000 - presentationTimeUs;

            mediaCodec.queueInputBuffer(index, 0 , data.length, pts, 0);
        }

        for (;;) {
            int outBufferIndex = mediaCodec.dequeueOutputBuffer(ebi, 0);
            Log.i(TAG, String.format("try to dequeue output buffer, oi=%d", outBufferIndex));
            if (outBufferIndex >= 0) {
                ByteBuffer bb = mediaCodec.getOutputBuffer(outBufferIndex);
                byte[] outData = new byte[ebi.size];

                bb.get(outData);

                try {
                    fileOutputStream.write(outData);

                } catch (IOException e) {
                    e.printStackTrace();
                }

                Log.i(TAG, "encode: bb --> " + ebi.size);

                //onEncodedAnnexbFrame(bb, ebi);
                mediaCodec.releaseOutputBuffer(outBufferIndex, false);
            }

            if (outBufferIndex < 0) {
                break;
            }
        }

    }



}
